<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;" v-loading="loading_search">
			<el-form :inline="true" :model="filters">
				<el-form-item>
				 	<el-input  placeholder="请输入学校" v-model="filters.schoolName"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="filters.adminName" placeholder="姓名"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-input v-model="filters.account" placeholder="账号"   style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-select v-model="filters.roleId" placeholder="请选择角色" style="width:150px;" clearable>
						<el-option v-for="(item,i) in roleList" :key="i" :label="item.roleName" :value="item.roleId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;">
			<el-table-column type="index" label="序号" width="50" align='center'>
				<template slot-scope="scope">   
                    {{pageSize*(nowPage-1)+scope.$index+1}}
                </template>
			</el-table-column>
			<el-table-column prop="adminName" label="姓名" min-width="120" align='center' sortable>
			</el-table-column>
			<el-table-column prop="account" label="用户账号" min-width="130" align='center' sortable>
			</el-table-column>
			<el-table-column prop="roleName" label="角色" min-width="150" align='center' sortable>
			</el-table-column>
			<el-table-column prop="schoolName" label="所属学校" min-width="200" align='center' sortable>
			</el-table-column>
			<el-table-column prop="useType" label="状态" width="50">
				<template slot-scope="scope">
					{{scope.row.useType=="0"?"正常":"停用"}}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="290" align='center' fixed="right" >
				<template slot-scope="scope">
					<el-button v-if="scope.row.roleLevel!='0'" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button v-if="scope.row.roleLevel!='0'" type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
					<el-button v-if="scope.row.useType==0 && scope.row.roleLevel!='0'" type="info" size="small" @click="offAdmin(scope.row)">停用</el-button>
					<el-button v-else-if="scope.row.roleLevel!='0'"  size="small" type="success" @click="onAdmin(scope.row)">启用</el-button>
					<el-button v-if="scope.row.roleLevel!='0'" type="warning" size="small" @click="resetpassword(scope.row)">重置</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="text-align: center; ">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" :before-close="closeDialog" v-loading="editLoading">
			<el-form :model="adminForm" label-width="120px" :rules="adminRules" ref="adminForm">
				<el-form-item label="管理员姓名：" prop="adminName">
					<el-input v-model="adminForm.adminName" placeholder="请输入管理员姓名，最长20个汉字" style="float:left;width:77%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号：" prop="phone">
					<el-input v-model="adminForm.phone" @keyup.native="validatePhone('adminForm')" placeholder="请输入手机号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				<el-form-item label="角色：" prop="roleId">
					<el-select v-model="adminForm.roleId" placeholder="请选择角色" @change="changeRole(adminForm.roleId)" style="float:left;width:77%;">
						<el-option v-for="(item,i) in roleList" :key="i" :label="item.roleName" :value="item.roleId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属地区：" required v-if="roleLevel == 2">
					<el-form-item prop="provinceCode" style="float:left;width:25%;">
						<el-select v-model="adminForm.provinceCode" @change="getCityListByProvince(adminForm.provinceCode,true)" placeholder="请选择省">
							<el-option v-for="(i,j) in provinceList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="cityCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="adminForm.cityCode" :disabled="adminForm.provinceCode==''" @change="getDistrictListByCity(adminForm.cityCode,true)" placeholder="请选择市">
							<el-option v-for="(i,j) in cityList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="districtCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="adminForm.districtCode" :disabled="adminForm.cityCode==''" @change="getSchoolListByCounty(true)" placeholder="请选择区/县">
							<el-option v-for="(i,j) in districtList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="所属学校：" prop="schoolId" v-if="roleLevel == 2">
					<el-select v-model="adminForm.schoolId" :disabled="adminForm.districtCode==''" placeholder="请选择所属学校"  style="float:left;width:77%;">
						<el-option v-for="(i,j) in schoolList" :label="i.schoolName" :value="i.schoolId" :key="j"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="closeDialog">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" :before-close="closeDialog" v-loading="addLoading">
			<el-form :model="adminForm" label-width="120px" :rules="adminRules" ref="adminForm">
				<el-form-item label="管理员姓名：" prop="adminName">
					<el-input v-model="adminForm.adminName" placeholder="请输入管理员姓名，最长20个汉字" style="float:left;width:77%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号：" prop="phone">
					<el-input v-model="adminForm.phone" @keyup.native="validatePhone('adminForm')" placeholder="请输入手机号" style="float:left;width:77%;"></el-input>
				</el-form-item>
				<el-form-item label="角色：" prop="roleId">
					<el-select v-model="adminForm.roleId" placeholder="请选择角色" @change="changeRole(adminForm.roleId)" style="float:left;width:77%;">
						<el-option v-for="(item,i) in roleList" :key="i" :label="item.roleName" :value="item.roleId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属地区：" required v-if="roleLevel == 2">
					<el-form-item prop="provinceCode" style="float:left;width:25%;">
						<el-select v-model="adminForm.provinceCode" @change="getCityListByProvince(adminForm.provinceCode,true)" placeholder="请选择省">
							<el-option v-for="(i,j) in provinceList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="cityCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="adminForm.cityCode" :disabled="adminForm.provinceCode==''" @change="getDistrictListByCity(adminForm.cityCode,true)" placeholder="请选择市">
							<el-option v-for="(i,j) in cityList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="districtCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="adminForm.districtCode" :disabled="adminForm.cityCode==''" @change="getSchoolListByCounty(true)" placeholder="请选择区/县">
							<el-option v-for="(i,j) in districtList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="所属学校：" prop="schoolId" v-if="roleLevel == 2">
					<el-select v-model="adminForm.schoolId" :disabled="adminForm.districtCode==''" placeholder="请选择所属学校"  style="float:left;width:77%;">
						<el-option v-for="(i,j) in schoolList" :label="i.schoolName" :value="i.schoolId" :key="j"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="closeDialog">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	import { SysApi } from '@/api/index'

	export default {
		data() {
			var checkPhone = (rule, value, callback) => {
				if (!value) {
					callback();
				} else {
					const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
					// console.log(reg.test(value));
					if (reg.test(value)) {
						callback();
					} else {
						return callback(new Error('请输入正确的手机号'));
					}
				}
			};
			return {
				filters: {
					schoolName:'',
					adminName:'',
					account:'',
					roleId:''
				},
				tableData: [],
				total: 0,
				listLoading: true,
				loading_search: true,

				//管理员信息表单
				adminForm: {
					adminId: '',
					adminName: '',
					phone: '',
					roleId: '',
					provinceCode: '',
					cityCode: '',
					districtCode: '',
					schoolId: '',
					type: '',
					useType: '',
					roleLevel: '',
				},

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
			
				adminRules: { //管理员信息表单验证
					adminName:[
						{ required: true, message: '请输入管理员姓名', trigger: 'blur' },
						{ min: 1, max: 20, message: '姓名长度为 1 到 20 个字符', trigger: ['blur','change'] }
					],
					phone:[
						{ required: true, message: '请输入管理员手机号', trigger:'blur' },
						{ validator: checkPhone, trigger: ['blur','change'] }
					],
					roleId:[
						{ required: true, message: '请选择角色', trigger: ['blur','change'] }
					],
					provinceCode:[
						{ required: true, message: '请选择省', trigger:  'blur' }
					],
					cityCode:[
						{ required: true, message: '请选择市', trigger:  'blur' }
					],
					districtCode:[
						{ required: true, message: '请选择区/县', trigger:  'blur' }
					],
					schoolId:[
						{ required: true, type: 'number',message: '请选择所属学校', trigger:  'blur' }
					]
            },
            roleList:[],
            pageSize:10,
            nowPage:1,
            provinceList:[],
            cityList:[],
            districtList:[],
            schoolList:[],
            roleLevel:0,

			}
		},
		created(){
			//获取管理员列表
			this.getUsers();
			//获取角色列表
			this.getRoleList();
			//获取省市县三级联动列表
			this.getProvinceList();
		},
		mounted() {
			 //获取管理员列表
			this.getUsers();
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.nowPage = val;
				this.getUsers();
			},
			//获取角色列表
			getRoleList(){
			SysApi.getRoleList({}, res => {
					this.roleList = res;
				}, (errorType, error) => {
				})
			},
			//获取省列表
			getProvinceList(){
				let params = {
					parentcode: '0'

				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.provinceList = res;
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			},
			//市相对省联动
			getCityListByProvince(parentcode,init){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.cityList = res;
					//console.log(init);
					if (init)
					{
						this.adminForm.cityCode =  '';
						this.adminForm.districtCode =  '';
						this.adminForm.schoolId = '';
					}
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			
			},
			//区相对市联动
			getDistrictListByCity(parentcode,init){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.districtList = res;
					//console.log(init);
					if (init)
					{
						this.adminForm.districtCode =  '';
						this.adminForm.schoolId = '';
					}
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
				
			},
			//学校相对所在地区联动
			getSchoolListByCounty(init){
				this.adminForm.schoolId =  '';
				let params = {
					provinceCode: this.adminForm.provinceCode,
					cityCode: this.adminForm.cityCode,
					districtCode: this.adminForm.districtCode
				}
				SysApi.getSchoolList(params,res =>{
					this.schoolList = res;
					//console.log(init);
					if (init)
					{
						this.adminForm.schoolId = '';
					}
				}, (errorType, error) => {})
			},
			//获取用户列表
			getUsers() {
				let params = {
					pageNum: this.nowPage,
					pageSize: this.pageSize,
					schoolName: this.filters.schoolName,
					adminName: this.filters.adminName,
					account: this.filters.account,
					roleId: this.filters.roleId,
				};
				this.listLoading = true;

				SysApi.getAllAdminListPage(params,res =>{
					this.total = res.total;
					this.tableData = res.list;
					this.listLoading = false;
				}, (errorType, error) => {
					this.listLoading = false;
				})


			},
			//管理员手机号，只能输入正整数限制
			validatePhone(str){
				this.adminForm.phone = this.adminForm.phone.replace(/[^\.\d]/g,'');
				this.adminForm.phone = this.adminForm.phone.replace('.','');
			},
			//改变角色
			changeRole(roleId){
				for(let i = 0; i < this.roleList.length; i++){
					if(this.roleList[i].roleId == roleId){
						this.roleLevel = this.roleList[i].roleLevel
						this.adminForm.roleLevel = this.roleList[i].roleLevel
					}
				}
			},
			//删除
			handleDel: function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					let params = {
						 adminId: row.adminId
						 };

					SysApi.deleteAdmin(params, res => {
						this.listLoading = false;
						this.$message({type: 'success', message: '删除成功'})
						this.getUsers();
					}, (errType, error) => {
					}).catch((error) => {
						this.listLoading = false;
					})
				}).catch(() => {
					this.listLoading = false;
				});
			},
			//显示编辑界面
			handleEdit: function (row) {
				this.editLoading = true;
				//this.schoolForm = Object.assign({}, row);
				this.changeRole(row.roleId)
				
				this.adminId = row.adminId;
				this.adminForm.adminId = row.adminId;
				this.adminForm.adminName = row.adminName;
				this.adminForm.roleId = row.roleId;
				this.adminForm.phone = row.phone;
				this.adminForm.adminName = row.adminName;
				this.adminForm.roleLevel = row.roleLevel;

				if (this.roleLevel==2){
					//console.log(this.roleLevel)
					this.adminForm.provinceCode = row.provinceCode;
					this.getCityListByProvince(row.provinceCode,false);
					this.adminForm.cityCode = row.cityCode;
					this.getDistrictListByCity(row.cityCode,false);
					this.adminForm.districtCode=row.districtCode;

					this.getSchoolListByCounty(false)
					this.adminForm.schoolId=row.schoolId
				}
				else
				{
					//console.log(this.roleLevel)
					this.adminForm.provinceCode = ''
					this.adminForm.cityCode = ''
					this.adminForm.districtCode = ''
					this.adminForm.schoolId = ''
				}

				this.editFormVisible = true;
				this.editLoading = false;
				//this.adminForm = Object.assign({}, row);
				
			},
			//显示新增界面
			handleAdd: function () {
				this.addLoading = true;
				this.adminForm.adminId =  '';
				this.adminForm.adminName =  '';
				this.adminForm.phone =  '';
				this.adminForm.roleId = '';
				this.adminForm.provinceCode =  '';
				this.adminForm.cityCode =  '';
				this.adminForm.districtCode =  '';
				this.adminForm.schoolId =  '';
				this.adminForm.roleLevel =  0;
				this.roleLevel = 0 ;
				this.addFormVisible = true;
				this.addLoading = false;
		
			},
			//编辑
			editSubmit: function () {
				this.$refs.adminForm.validate((valid) => {
					if (valid) {
							
							let params = Object.assign({}, this.adminForm);
							//console.log(params);
							SysApi.saveAdmin(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['adminForm'].resetFields();
								this.editFormVisible = false;
								this.getUsers();
							}, (errorType, error) => {
											
							}).catch((error) => {

							})
							
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.adminForm.validate((valid) => {
					if (valid) {
							
							let params = Object.assign({}, this.adminForm);
							//console.log(params);
							SysApi.saveAdmin(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['adminForm'].resetFields();
								this.addFormVisible = false;
								this.getUsers();
							}, (errorType, error) => {
		
							}).catch((error) => {

							})
						
					}
				});
			},
			closeDialog: function () {
				
				this.$refs['adminForm'].resetFields();
				this.editFormVisible = false;
				this.addFormVisible = false;
			},
			resetpassword(row){
				this.$confirm('是否重置密码', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					//console.log(row.adminId)
					SysApi.resetAdminPassword({
						adminId: row.adminId
					}, res => {
						this.$message({type: 'success', message: '重置密码成功!'})
						this.getUsers();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '重置密码失败!'})
					}).catch((error) => {
						
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			onAdmin(row){
				this.$confirm('是否启用管理员?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.onAdmin({
						adminId: row.adminId
					}, res => {
						this.$message({type: 'success', message: '启用成功!'})
						this.getUsers();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '启用失败!'})
					}).catch((error) => {
						
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			offAdmin(row) {
				this.$confirm('是否停用管理员?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.offAdmin({
						adminId: row.adminId
					}, res => {
						this.$message({type: 'success', message: '停用成功!'})
						this.getUsers();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '停用失败!'})
					}).catch((error) => {
						
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			}
			
		},
		
	}

</script>

<style>
.el-table >.el-table__fixed {
    height: 100% !important; 
  }
.el-table >.el-table__fixed-right {
    height: 100% !important; 
  }
.el-table--scrollable-x .el-table__body-wrapper {
    z-index: 1;
  }
</style>